import React from "react"
import {compose, lifecycle, withHandlers, withState} from "recompose"
import {get, postParam} from "server"
import {message} from "antd";

const pageSize = 40

const libraryCompose = compose(
  withState('loading', '$loading', false),
  withState('drawerVisible', '$drawerVisible', false),
  withState('pagination', '$pagination', {total: 0, pageSize, current: 1}),
  withState('searchKey', '$searchKey', ''),
  withState('dataSource', '$dataSource', []),
  withState('initData', '$initData', {
    season: [
      {value: 'spring', text: '春'},
      {value: 'summer', text: '夏'},
      {value: 'autumn', text: '秋'},
      {value: 'winter', text: '冬'}
    ]
  }),
  withHandlers({
    toggleDrawer: ({$drawerVisible}) => {
      return (visible) => {
        return () => {
          $drawerVisible(visible)
        }
      }
    }
  }),
  withHandlers({
    getPageData: ({$pagination, pagination, $loading, $dataSource}) => {
      return (param, pageNum) => {
        $loading(true)
        const requestParam = param || {}
        requestParam.type = 'platform'
        requestParam.havePicture = true
        //版型库只查询上架中
        requestParam.availabel = true
        get(`/clothing/page/${pageSize}/${pageNum || 1}`, requestParam)
          .then(page => {
            $dataSource(page.pageData)
            pagination.total = page.total
            pagination.current = pageNum || 1
            $pagination(Object.assign({}, pagination))
          }).finally(() => {
          $loading(false)
        })
      }
    }
  }),
  withHandlers({
    onFastSearch: ({getPageData, $searchKey}) => {
      return (key) => {
        $searchKey(key)
        getPageData({key})
      }
    },
    onPageChange: ({searchKey, getPageData}) => {
      return (page) => {
        getPageData({key: searchKey || ''}, page)
      }
    },
    addFavorite: ({$dataSource, dataSource}) => {
      return (data) => (e) => {
        e.stopPropagation()
        postParam(`/favorite/${data.id}`, {})
          .then(res => {
            if (res.id) {
              $dataSource(dataSource.map(d => {
                if (d.id === data.id) {
                  d.collected = true
                }
                return d
              }))
              message.success(<span><b>{data.code}</b>收藏成功!</span>)
            }
          })
      }
    }
  }),
  lifecycle({
    componentDidMount() {
      const {getPageData} = this.props
      getPageData()
    }
  })
)

export default libraryCompose